package cn.hdu.liang.proandcon;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class MyService {
    private ReentrantLock lock = new ReentrantLock();
    private Condition cond = lock.newCondition();
    private boolean hasValue = false;
    private int value;

    public void set(int value) {
        try {
            lock.lock();
            while(hasValue == true) {
                cond.await();
            }
            this.value = value;
            System.out.println("打印" + value);
            hasValue = true;
            cond.signal();
        } catch(InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void get() {
        try {
            lock.lock();
            while(hasValue == false) {
                cond.await();
            }
            System.out.println("消费" + value);
            hasValue = false;
            cond.signal();
        } catch(InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
